package com.lyz.redisDelayQueue.service.impl;


import com.lyz.redisDelayQueue.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

/**
 * @author EDZ
 * 基本上传
 */
@Slf4j
@Service
public class UploadServiceImpl implements UploadService {

    @Value("${file-path}")
    private String fileath;

    @Override
    public String url(@RequestParam("file") MultipartFile file) {
        //   192.168.116.1:\fileItem\联盟网站数据库设计001.png
        String fileName = file.getOriginalFilename();
        //获取当前时间戳
        long timeStamp = System.currentTimeMillis();
        String timeKey = String.valueOf(timeStamp);
        //获取文件类型后缀
        int one = fileName.lastIndexOf(".");
        String Suffix = fileName.substring((one + 1), fileName.length());
        //  png
        fileName = timeKey + "." + Suffix;
        //获取年月日创建文件夹
        Calendar now = Calendar.getInstance();
        String year = String.valueOf(now.get(Calendar.YEAR));
        String month = String.valueOf(now.get(Calendar.MONTH) + 1);
        String date = String.valueOf(now.get(Calendar.DATE));
        String myurl = year + "/" + month + "/" + date + "/";
        String fileDir = fileath + myurl;

        File dest = new File(fileDir);
        if (!dest.exists() && !dest.isDirectory()) {
            dest.mkdirs();
        }

        String url = "/" + myurl + fileName;
        File newFile = new File(fileDir + fileName);
        try {
            file.transferTo(newFile);
            System.out.println(url);
            return url;

        } catch (IOException e) {
            log.error(e.toString(), e);
        }
        return "上传失败";
    }
}
